package com.yzy.fly.boot;

import com.yzy.fly.FlyEnvContext;
import com.yzy.fly.FlyEnvMap;
import com.yzy.fly.config.FlySpringTransactionAnnotationParser;
import com.yzy.fly.config.FlyTransaction;
import com.yzy.fly.config.properties.FlyProperties;
import com.yzy.fly.config.properties.TransactionConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.List;

@Order(value = 60)
@Slf4j
@Component
@ConditionalOnProperty(prefix = "fly.configuration.transaction", name = "enable", havingValue = "true", matchIfMissing = true)
public class FlyTransactionCommandLineRunner implements CommandLineRunner {

    @Autowired(required = false)
    private FlyProperties flyProperties;
    //    @Autowired
//    private TransactionAttributeSource transactionAttributeSource;
    @Autowired
    private FlySpringTransactionAnnotationParser flySpringTransactionAnnotationParser;
    @Autowired
    private FlyTransactionService flyTransactionService;
//    @Autowired
//    private FlyCrudService<Long, FlyTransactionAttribute> flyTransactionAttributeService;

    @Override
    public void run(String... args) throws Exception {
        String startupId = FlyEnvContext.get("startupId");

        String appId = "";
        TransactionConfiguration transactionConfig = new TransactionConfiguration();
        if (flyProperties != null) {
            transactionConfig = flyProperties.getConfiguration().getTransaction();
            appId = flyProperties.getConfiguration().getAppId();
        }

        boolean dbEnable = transactionConfig.isDbEnable();
        if (dbEnable) {
            List<FlyTransaction> transactionInfos = flySpringTransactionAnnotationParser.getTransactionInfos();
            for (int i = 0; i < transactionInfos.size(); i++) {
                FlyTransaction flyTransaction = transactionInfos.get(i);
                flyTransaction.setAppId(appId);
                flyTransaction.setStartupId(startupId);
                flyTransactionService.saveRole(flyTransaction);
            }
        }

    }

}
